package com.whub507.msgmanager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whub507.msgmanager.common.ResResult;
import com.whub507.msgmanager.common.vo.ApprovingProjectVO;
import com.whub507.msgmanager.domain.Message;
import com.whub507.msgmanager.domain.Project;
import com.whub507.msgmanager.domain.User;
import com.whub507.msgmanager.mapper.MessageMapper;
import com.whub507.msgmanager.mapper.ProjectMapper;
import com.whub507.msgmanager.mapper.UserMapper;
import com.whub507.msgmanager.service.ProjectService;
import com.whub507.msgmanager.utils.TimeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Resource
    ProjectMapper projectMapper;
    @Resource
    MessageMapper messageMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public Boolean insertProject(Project project) {
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            project.setCreatetime(now.format(formatter));
//            project.setInvalidtime(now.plusMinutes(15).format(formatter));

            project.setStatus(0);// 0待审批， 1审批中

            Project tmp = projectMapper.selectByNameAndSenderId(project.getName(), project.getSenderid());

            if (tmp != null)
                return Boolean.FALSE;

            projectMapper.insertProject(project);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    @Override
    public List<Project> searchProject(String keyWord, Integer userId){
        if (keyWord == null || keyWord.equals(""))
            return projectMapper.selectAllProject(userId);
        List<Project> projects = projectMapper.selectAllByKeyWord(keyWord);
        return projects;
    }

    @Override
    public List<Project> listAllProject(Integer userId){
        List<Project> updateStatus = projectMapper.selectAllProject(userId);
        Date now = new Date();
        List<Project> invalids = updateStatus.stream().filter(p -> {
            try {
                return TimeUtils.string2Date(p.getInvalidtime()).before(now);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        invalids.stream().forEach(p ->{
            p.setStatus(2);
            projectMapper.updateProjectById(p);
        });

        return projectMapper.selectAllProject(userId);
    }

    @Override
    public Project getProjectByName(String name) {
//        LambdaQueryWrapper<Project> projectQueryWrapper=new LambdaQueryWrapper<>();
//        projectQueryWrapper.eq(Project::getName,name);
        Project project=projectMapper.selectByName(name);
        if(project!=null){
            Integer pid=project.getId();
//            LambdaQueryWrapper<Message> msgQueryWrapper=new LambdaQueryWrapper<>();
//            msgQueryWrapper.eq(Message::getProjectid,pid);
            List<Message> messageList=messageMapper.selectAllByProjectId(pid);
//            project.setMessageList(messageList);
        }
        return project;
    }

    @Override
    public Boolean deleteProjects(List<String> projectNames, Integer senderId){
        for (int i = 0; i < projectNames.size(); i++) {
            Project project = projectMapper.selectByNameAndSenderId(projectNames.get(i), senderId);
            projectMapper.deleteProjectById(project.getId());
        }
        return Boolean.TRUE;
    }

    @Override
    public List<ApprovingProjectVO> getApproveProjects(Integer userId) {
//        User user = userMapper.selectById(userId);
//        if (!user.getRole().equals("处负责人"))
//            return ResResult.error(507, "该用户不是处负责人");

        List<Project> projects = projectMapper.selectApproveProjects(userId);

        List<ApprovingProjectVO> res = new ArrayList<>();

        projects.stream().forEach(p -> {
            User user = userMapper.selectById(p.getSenderid());
            res.add(new ApprovingProjectVO(p.getId(), p.getName(), p.getDetail(), p.getInvalidtime(), p.getType(), user.getUsername()));
        });

        return res;
    }

    @Override
    public String updateProjectsStatus(List<Integer> projectIds, Integer status) {
        try {
            projectIds.stream().forEach(p ->{
                projectMapper.updateProjectById(new Project(p, status));
            });
        } catch (Exception e){
            return "出现错误:"+e.getMessage();
        }
        return "修改成功";
    }

    @Override
    public String reUploadProject(Project project) {
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            project.setCreatetime(now.format(formatter));

            project.setStatus(0);// 0待审批， 1审批通过， 2有效时间已过， 3审批不通过

            projectMapper.updateProjectById(project);
            return "重新上传成功";
        }catch (Exception e){
            return "出现错误:"+e.getMessage();
        }
    }


}
